<?php

namespace Gaolei\WechatPay;

use Gaolei\WechatPay\lib\Wechat;

class Closer extends Wechat
{

    // 关闭订单 的 WECHAT 官方接口地址
    protected const MAKE_PACKAGE_URL = 'https://api.mch.weixin.qq.com/pay/closeorder';

    /**
     * 关闭订单
     * @param string $orderNo 商户订单编号
     * @return array
     * @throws \Exception
     */
    public function doClose(string $orderNo): array
    {
        try{
            $package['appid'] = $this->appId;                    // 公众号 APPID
            $package['mch_id'] = $this->mchId;                   // 支付商户号
            $package['nonce_str'] = $this->createNonceStr();     // 随机字符串
            $package['out_trade_no'] = $orderNo;                 // 商家订单号
            ksort($package, SORT_STRING);
            $package['sign'] = $this->getSign($package, $this->apiKey);     // 数据签名
            // 数据包转 xml 格式
            $xmlPackage = $this->arrayToXml($package);
            $responseXml = $this->curlPost(self::MAKE_PACKAGE_URL, $xmlPackage);
            // 禁止引用外部xml实体
            libxml_disable_entity_loader(true);
            $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
            $result = $this->xmlToArray($unifiedOrder);
            if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
                return ['code' => 200, 'msg' => '操作成功'];
            }
            return ['code' => 400, 'msg' => '操作失败', 'data' => $result];
        }catch (\Throwable $t){
            return ['code' => 500, 'msg' => '操作错误', 'data' => [
                'file' => $t->getFile(), 'line' => $t->getLine(), 'error' => $t->getMessage()
            ]];
        }
    }

}